package handler

import (
	"apibe/grpc/rome/v1/service"
	"apibe/grpc/rome/v1/service/impl"
	"apibe/grpc/rome/v1/share/crypt"
	"context"
	"errors"
	"go.mongodb.org/mongo-driver/bson"
)

// 注册
func RegisterHandler(u *impl.User, ip string) error {
	claims := &crypt.CustomClaims{}
	claims.UserName = u.NickName + "-Register"
	claims.Account = u.Account
	claims.Ip = ip
	_, err := u.UpsertOne(claims)
	if err != nil {
		return errors.New("This account has been registered ")
	}
	return nil
}

// 修改用户
func UserUpdateHandler(u *impl.User, claims *crypt.CustomClaims) error {
	_, err := u.UpsertOne(claims)
	return err
}

// 登录
func LoginHandler(account string, password string, ip string) (u *impl.User, err error) {
	userService, err := service.NewService(service.UserService)
	if err != nil {
		return nil, err
	}
	claims := &crypt.CustomClaims{}
	claims.UserName = account + "  login"
	claims.Account = account
	claims.Ip = ip
	result := userService.FindOneFilter(bson.M{"account": account, "password": password})
	err = result.Decode(&u)
	if err != nil {
		return nil, errors.New(" Account Verification Failed ")
	}
	return u, err
}

// UserFindManyHandler 批量查询
func UserFindManyHandler(filter map[string]interface{}, page int, pageSize int) (*[]impl.User, int64, error) {
	userService, err := service.NewService(service.UserService)
	if err != nil {
		return nil, 0, err
	}
	cursor, total, err := userService.FindManyFilter(filter, page, pageSize)
	if err != nil {
		return nil, 0, err
	}
	var us []impl.User
	err = cursor.All(context.Background(), &us)
	if err != nil {
		return nil, 0, err
	}
	for i, u := range us {
		u.AddLogger()
		us[i] = u
	}
	return &us, total, err
}
